<?php
$pageTitle = "编辑用户";
include 'header.php';

// 获取用户ID
if (!isset($_GET['id'])) {
    header('Location: users.php');
    exit;
}

$userId = $_GET['id'];

// 不允许编辑自己
if ($userId == $_SESSION['user_id']) {
    header('Location: users.php');
    exit;
}

// 获取用户信息
try {
    $stmt = $pdo->prepare('SELECT id, username, school, created_at FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        header('Location: users.php');
        exit;
    }
} catch (PDOException $e) {
    die('数据库查询失败: ' . $e->getMessage());
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $school = $_POST['school'];

    // 如果提供了新密码，则更新密码
    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $sql = 'UPDATE users SET username = ?, password = ?, school = ? WHERE id = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$username, $password, $school, $userId]);
    } else {
        $sql = 'UPDATE users SET username = ?, school = ? WHERE id = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$username, $school, $userId]);
    }

    // 重定向回用户详情页面
    header('Location: users.php');
    exit;
}
?>
    <div class="row">
        <h1 class="mb-4">编辑用户：<?= htmlspecialchars($user['username']) ?></h1>
        
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">编辑用户信息</h5>
                <form method="post">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" name="username" value="<?= htmlspecialchars($user['username']) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="school" class="form-label">学校</label>
                        <input type="text" class="form-control" id="school" name="school" value="<?= htmlspecialchars($user['school']) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">新密码（留空则不修改）</label>
                        <input type="password" class="form-control" id="password" name="password">
                    </div>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </form>
            </div>
        </div>

        <div class="mt-3">
            <a href="users.php" class="btn btn-outline-secondary">返回用户列表</a>
        </div>
    </div>

<!-- 引入Bootstrap JS -->
<?php include 'footer.php'; ?>